'use strict';

superApp.controller('AuthController', function ($scope, $q, AuthService, $log, $cookieStore, $location) {
	var initSession = $q.defer();

	$scope.showValidationMessages = false;

	initSession.promise.then(createUserSession);

	function createUserSession(response) {
		$scope.userAuth.username = response.user.username;
		$scope.userAuth.fullName = response.user.name + ' ' + response.user.lastname;
		$scope.userAuth.isConnected = true;

		$log.info($scope.userAuth);

		$cookieStore.put('isConnected', true);
		$cookieStore.put('userAuthData', response.user);

		$location.path('/users');
	};

	$scope.login = function() {
		$scope.showValidationMessages = true;

		var response = AuthService.session.login({
			username: $scope.user.username, 
			password: $scope.user.password
		})
		.$promise.then(function(response) {
			if (!response.error && response.user != null) {
				initSession.resolve(response);
			} else {
				alert('Error, try again.');
			}
		});
	};
	
});